<?php
/**
 * 答题
 * User: cxm
 * Date: 2021/1/9
 * Time: 10:42
 */

namespace App\Http\Controllers\Home;


use App\Models\Activity;
use App\Models\AwardHistory;
use App\Models\Question;
use App\Models\SystemConfig;
use App\Models\UserQuestion;
use App\Models\UserQuestionAnswer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class QuestionController extends Controller {
    /**
     * 删除记录
     */
    public function deleteRecord(){
        // 查看用户答题组
        $result = UserQuestion::whereRaw("UNIX_TIMESTAMP(now()) > UNIX_TIMESTAMP(created_at) + 1800")
                    ->get()->toArray();
        if ($result) {
            $user_question_ids = array_column($result,'id');
            // 用户题组
            UserQuestion::whereIn('id',$user_question_ids)->forceDelete();
            // 用户答题记录
            UserQuestionAnswer::whereIn('user_question_id',$user_question_ids)->forceDelete();
        }
    }

    /**
     * 获取题
     * URL POST:/api/home/question/getLists
     * @param Request $request
     * @param int user_question_id
     * @return mixed
     */
    public function getQuestions(Request $request){
        // 删除记录
        // $this->deleteRecord();
        $params = $request->only(['user_question_id']);
        $user_question_id = isset($params['user_question_id']) ? $params['user_question_id'] : 0;
        if ($user_question_id > 0) {
            $user_question = UserQuestion::find($params['user_question_id']);
            $user_question['questions'] = json_decode($user_question['questions'],true);
            return $this->success('查询成功',$user_question);
        }
        // 用户信息
        $user = $this->userModel();
        // 获取平台设置的数量
        $question_num = SystemConfig::getSingleValue('question_num');
        $params['take'] = $question_num;
        // 选项
        $params['with'][] = 'options:question_id,option,content';
        // 状态为显示
        $params['where'][] = ['status',1];
        // 字段
        $params['field'] = ['id','title','answer','status','created_at'];
        // 排序 随机
        $params['random'] = true;
        // 按设置的数量随机获取题
        $questions = Question::getAll($params);
        if (count($questions) != $question_num) {
            return $this->error('题数量不对');
        }
        $data['questions'] = $questions;
        // 加入答题组记录
        $user_question_id = UserQuestion::insertGetId([
            'user_id'       => $user['id'],
            'questions'     => json_encode($questions),
            'created_at'    => Carbon::now()
        ]);
        $data['user_question_id'] = $user_question_id;
        return $this->success('查询成功',$data);
    }

    /**
     * 保存答案
     * URL POST:/api/home/question/saveAnswer
     * @param Request $request
     * @param int user_question_id 用户题组ID
     * @param int question_id 题ID
     * @param string answer 答案
     * @return mixed
     */
    public function saveAnswer(Request $request){
        $params = $request->only(['user_question_id','question_id','answer']);
        $validator = Validator::make($params,[
            'user_question_id'          => ['required'],
            'question_id'               => ['required'],
            'answer'                    => ['required']
        ],[
            'user_question_id.required' => '用户题组ID是必须的',
            'question_id.required'      => '题ID是必须的',
            'answer.required'           => '题答案是必须的'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        // 查看用户题组是否生成
        $user_question = UserQuestion::find($params['user_question_id']);
        if (!$user_question) {
            return $this->error('用户答题信息错误');
        }
        // 查询题ID
        $question = Question::find($params['question_id']);
        if (!$question) {
            return $this->error('题信息不存在');
        }
        $params['right_answer'] = $question->answer;
        $params['created_at'] = Carbon::now();
        $result = UserQuestionAnswer::insert($params);
        if ($result === false) {
            return $this->error('保存失败');
        }
        return $this->success('保存成功');
    }

    /**
     * 保存答案 所有的题
     * URL POST:/api/home/question/saveAllAnswer
     * @param Request $request
     * @param int user_question_id 用户题组ID
     * @param array answer 题答案数组 [[1,'A'],[2,'B'],……]
     * @return mixed
     */
    public function saveAllAnswer(Request $request){
        $params = $request->only(['user_question_id','answer']);
        $params['answer'] = json_decode($params['answer'],true);
        $validator = Validator::make($params,[
            'user_question_id'          => ['required'],
            'answer'                    => ['required','array']
        ],[
            'user_question_id.required' => '用户题组ID是必须的',
            'answer.required'           => '题答案是必须的',
            'answer.array'              => '题答案格式错误'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        // 查看用户题组是否生成
        $user_question = UserQuestion::find($params['user_question_id']);
        if (!$user_question) {
            return $this->error('用户答题信息错误');
        }
        $questionIds = array_column($params['answer'],0);
        $question_arr = Question::getAnswer($questionIds);
        // 删除之前的答题记录
        UserQuestionAnswer::where('user_question_id',$params['user_question_id'])->forceDelete();
        $data = $status = [];

        foreach ($params['answer'] as $item) {
            $status[] = ($item[1] != $question_arr[$item[0]]) ? 'false' : 'true';
            $data[] = [
                'user_question_id'          => $params['user_question_id'],
                'question_id'               => $item[0],
                'answer'                    => $item[1],
                'right_answer'              => $question_arr[$item[0]],
                'created_at'                => Carbon::now()
            ];
        }
        $result = UserQuestionAnswer::insert($data);
        if ($result === false) {
            return $this->error('题答案保存失败');
        }
        if (in_array('false',$status)) {
            return $this->error('很遗憾，没有全部答对');
        }
        return $this->success('操作成功');
    }

    /**
     * 答题是否通过（全对）
     * URL POST:/api/home/question/isRight
     * @param Request $request
     * @param int user_question_id 用户题组ID
     * @return mixed
     */
    public function isRight(Request $request){
        $params = $request->only(['user_question_id']);
        if (!array_key_exists('user_question_id',$params) || empty($params['user_question_id'])) {
            return $this->error('缺少用户题组ID');
        }
        $error_question = UserQuestionAnswer::errorNum($params['user_question_id']);
        if (!empty($error_question)) {
            return $this->success('错误题',$error_question,4001);
        }
        return $this->success('恭喜你全部答对！');
    }

    /**
     * 用户答题抽奖情况---是否可以参与抽奖
     * URL POST:/api/home/question/checkUserVie
     * @param Request $request
     * @param int activity_id 活动ID
     * @return mixed
     */
    public function checkUserVie(Request $request){
        $params = $request->only(['activity_id']);
        $params['activity_id'] = 2;
        if (!array_key_exists('activity_id',$params) || empty($params['activity_id'])) {
            return $this->error('缺少活动ID');
        }
        $activity = Activity::find($params['activity_id']);
        if (!$activity) {
            return $this->error('活动不存在');
        }
        // 判断活动是否结束
        if (!empty($activity['start_time']) && time() < strtotime($activity['start_time'])) {
            return $this->error('活动还没有开始，请耐心等待……');
        }
        if (!empty($activity['end_time']) && time() > strtotime($activity['end_time'])) {
            return $this->error('活动已结束，您来晚了…………');
        }
        // 用户信息
        $user = $this->userModel();
        // 查询用户当天是否做过题
        $userQuestion = UserQuestion::where('user_id',$user['id'])->whereDate('created_at',date('Y-m-d'))->first();
        if (!$userQuestion) {
            return $this->error('你还没有答题',4001);
        }
        // 查看用户是否答题
        $isAnswer = UserQuestionAnswer::detail(['user_question_id'=>$userQuestion['id']]);
        if (!$isAnswer) {
            $data['user_question_id'] = $userQuestion['id'];
            return $this->success('查询成功',$data);
        }
        $activity_name = SystemConfig::getSingleValue('question_name');
        // 查看答题情况
        $userQuestionAnswer = UserQuestionAnswer::errorNum($userQuestion['id']);
        if ($userQuestionAnswer) {
            return $this->error('你今天已经参与'.$activity_name.'活动了，很遗憾，没有全部答对！',4002);
        }
        //  用户是否已中奖
        $prize_info = AwardHistory::userPrizeInfo($user['id'],$params['activity_id']);
        if ($prize_info) {
            return $this->error('抱歉，您的抽奖次数用完了',4003);
        }
        // 查看当天用户是否参与抽奖
        $day_in = AwardHistory::userDayPartake($user['id'],$params['activity_id']);
        if ($day_in) {
            return $this->error('您今天的抽奖次数用完了，请明天在来');
        }
        return $this->success('可以抽奖');
    }
}